package org.devio.rn.splashscreen;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.camera2.CameraManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * SplashScreen
 * 启动屏
 * from：http://www.devio.org
 * Author:CrazyCodeBoy
 * GitHub:https://github.com/crazycodeboy
 * Email:crazycodeboy@gmail.com
 */
public class SplashScreen {
    private static Dialog mSplashDialog;
    private static WeakReference<Activity> mActivity;
    private static File file;

    

    /**
     * 打开启动屏
     */
    public static void show(final Activity activity, final int themeResId, final String url) {
        if (activity == null) return;
        mActivity = new WeakReference<Activity>(activity);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!activity.isFinishing()) {
                    mSplashDialog = new Dialog(activity, themeResId);
                    LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    RelativeLayout ll_Layout = (RelativeLayout) inflater.inflate(R.layout.launch_screen, null);
                    final ImageView imageView = ll_Layout.findViewById(R.id.launchImage);
                    try{
                        Log.i("splash-url", url);
                        if(!TextUtils.isEmpty(url) && url.startsWith("http")){
                            String[] urlClick = url.split(";");
                            String picUrl = "";
                            String clickUrl = "";
                            if(urlClick.length > 0){
                                picUrl = urlClick[0];
                                if(urlClick.length == 2){
                                    clickUrl = urlClick[1];
                                }
                                Log.i("splash-clickUrl", clickUrl);
                                String[] filePath = picUrl.split("/");
                                if(filePath.length > 0){
                                    String fileNameType = filePath[filePath.length - 1];
                                    String[] fileNameString = fileNameType.split("\\.");
                                    if(fileNameString.length>0){
                                        String fileName = fileNameString[0];
                                        boolean isExist = existFile(fileName);
                                        if(isExist){
                                            String filePathLocal = getExternalStorageStatePath("splashscreen") + fileName+ ".jpg";
                                            Bitmap bitmap = loadBitmap(filePathLocal);
                                            if(bitmap!=null){
                                                imageView.setImageBitmap(bitmap);
                                                final String finalClickUrl = clickUrl;
                                                imageView.setOnClickListener(new View.OnClickListener() {
                                                    public void onClick(View v) {
                                                        if (v.equals(imageView)) {
                                                            // Write your awesome code here
                                                            if(finalClickUrl.startsWith("http")){
                                                                Intent intent = new Intent();
                                                                intent.setAction("android.intent.action.VIEW");
                                                                Uri content_url = Uri.parse(finalClickUrl);
                                                                intent.setData(content_url);
                                                                activity.startActivity(intent);
                                                            }
                                                        }
                                                    }
                                                });

                                            }else {

                                            }
                                        }else {

                                        }
                                    }

                                }
                            }

                        }
                    }catch (Exception e){

                    }



                    mSplashDialog.setContentView(ll_Layout);
                    mSplashDialog.setCancelable(false);

                    if (!mSplashDialog.isShowing()) {
                        mSplashDialog.show();
                    }
                }
            }
        });
    }

    // bitmap------>位图
    public static void getBitmap(String uri) {
        HttpURLConnection connection = null;
        InputStream inputStream=null;
        OutputStream outputStream=null;
        try {
            // 1、获得图片的url
            URL url = new URL(uri);

            // 2、获得网络连接
            connection = (HttpURLConnection) url.openConnection();

            if (connection.getResponseCode()==200){
                inputStream=connection.getInputStream();
            }else {
                return;
            }
            outputStream=new FileOutputStream(file);
            int length=0;
            byte[] buffer=new byte[4*1024];
            while ((length=inputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,length);
            }
            inputStream.close();
            outputStream.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 5、关闭网络连接
        finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public static Bitmap loadBitmap(String picturePath) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(picturePath, opt);
        if (bitmap == null) {
           // throw new FileNotFoundException("Couldn't open " + picturePath);
        }
        return bitmap;
    }

    /**
     * 创建一个文件
     */
    public static File createFile(String folderPath, String fileName) {
        File destDir = new File(folderPath);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        return new File(folderPath, fileName);
    }


    /***
     * 创建一个新的图片文件
     * 拍照后立即创建一个新的图片文件
     */
    private static boolean existFile(String fileName) {
        file = createFile(getExternalStorageStatePath("splashscreen"), fileName+ ".jpg");
        try {
            if (!file.exists()){
                file.createNewFile();
                return false;
            }
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    /**
     * 获取外部存储设备路径
     */
    public static String getExternalStorageStatePath(String folder) {
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);

        String folderPath = "";
        if (sdCardExist) {
            folderPath = Environment.getExternalStorageDirectory() + File.separator + folder + File.separator;
        } else {
            folderPath = "";
        }
        return folderPath;
    }

    /**
     * 打开启动屏
     */
    public static void show(final Activity activity, final boolean fullScreen, final String fullScreenUrl) {
        int resourceId = fullScreen ? R.style.SplashScreen_Fullscreen : R.style.SplashScreen_SplashTheme;

        show(activity, resourceId, fullScreenUrl);
    }

    /**
     * 打开启动屏
     */
    public static void show(final Activity activity, String fullScreenUrl) {
        show(activity, false, fullScreenUrl);
    }

    /**
     * 关闭启动屏
     */
    public static void hide(Activity activity) {
        if (activity == null) {
            if (mActivity == null) {
                return;
            }
            activity = mActivity.get();
        }

        if (activity == null) return;

        final Activity _activity = activity;

        _activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mSplashDialog != null && mSplashDialog.isShowing()) {
                    boolean isDestroyed = false;

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        isDestroyed = _activity.isDestroyed();
                    }

                    if (!_activity.isFinishing() && !isDestroyed) {
                        mSplashDialog.dismiss();
                    }
                    mSplashDialog = null;
                }
            }
        });
    }
}
